<template>
  <div class="app-container">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm">
      <el-form-item label="公告名称" required prop="title">
        <el-input v-model="ruleForm.title" style="width: 300px;" />
      </el-form-item>
      <el-form-item label="正文" prop="textContent">
        <editor-bar
          v-model="ruleForm.textContent"
          style="width: 800px; margin-left: 0;"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import EditorBar from '@/components/wangEnduit/index'
import { saveAnnounce, getAnnounceDetail } from '@/api/operate'

export default {
  components: { EditorBar },
  data() {
    return {
      isClear: false,
      ruleForm: {
      },
      rules: {
        title: [
          { required: true, message: '请输入公告名称', trigger: 'blur' },
          { max: 30, message: '最多30个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    const { name, params: { id }} = this.$route
    if (name === 'announce-edit') {
      this.getDetail(id)
    }
  },
  methods: {
    async getDetail(id) {
      try {
        const res = await getAnnounceDetail({
          id: Number(id)
        })
        if (res) {
          this.ruleForm = res
        }
      } catch (err) {
        console.log('接口出错')
      }
    },
    submitForm(formName) {
      const { name } = this.$route
      const that = this
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.ruleForm))
          const res = await saveAnnounce(params)
          if (res && typeof res === 'boolean') {
            this.$alert(`${name === 'announce-edit' ? '编辑' : '新增'}公告成功！`, {
              confirmButtonText: '确定',
              callback: action => {
                that.$router.push('/operate/announce')
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    onEditorChange(e) {
    }
  }
}
</script>
<style scoped lang="less">
  .app-container {
    background: #fff;
    overflow: auto;
  }
  .ql-editor-preview {
    position: absolute;
    top: 35px;
    right: 30px;
    width: 375px;
    height: 585px;
    border: 1px solid #ccc;
    background: #fff;
    padding: 15px;
    font-size: 16px;
    line-height: 20px;
    overflow: auto;
  }
  .ql-editor-preview ::v-deep p {
    margin: 0 0 5px 0;
    padding: 0;
    font-size: 16px;
    line-height: 20px;
  }
  .ql-editor-preview ::v-deep img {
    width: 100%;
  }
</style>
